<template>
  <TabSwitcher :tabs="['考试趋势', '考试记录']" @tab-change="handleTabChange">
    <template #tab-0>
      <div class="container">
        <div class="score-content">
          <div class="flex flex-align-center flex-justify-between" style="padding: 0 3%">
            <div class="score-title">小车科目一考试成绩</div>
            <!-- <div class="flex flex-align-center cursor_pointer" @click="clearModel = true">
              <el-icon size="2.1875rem">
                <Delete />
              </el-icon>
              <div class="font26 marL8">清空记录</div>
            </div> -->
          </div>
          <div ref="chartRef" class="chartStyle"></div>
        </div>
      </div>
    </template>
    <template #tab-1>
      <div class="container">
        <div class="score-content">
          <div class="grid bgTitle">
            <div class="f35">成绩</div>
            <div class="f35">用时</div>
            <div class="flex flex-align-center cursor_pointer" @click="timeOrder">
              <div class="f35">时间</div>
              <div class="flex flex-column">
                <el-icon :color="orderIndex == 0 ? '' : '#d9d9d9'">
                  <CaretTop />
                </el-icon>
                <el-icon :color="orderIndex == 1 ? '' : '#d9d9d9'">
                  <CaretBottom />
                </el-icon>
              </div>
            </div>
            <div class="f35">状态</div>
          </div>
          <div>
            <div class="grid ranking" v-for="(item, index) in scoreList" :key="index">
              <div class="score_ft">{{ item.score }}</div>
              <div class="fh35">{{ formatDuration((45 * 60) - item.seconds) }}</div>
              <div class="fh35">{{ item.time }}</div>
              <div :class="item.score >= 90 ? 'pass' : 'tips'">{{ item.score >= 90 ? '合格' : '不合格' }}</div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </TabSwitcher>
  <div class="score_bg">
    <div class="scoreInfo flex flex-align-center flex-justify-between">
      <div class="flex">
        <img :src="userStore.storeInfo.avatar" alt="" class="headerPic" />
        <div class="marL40">
          <div class="phone">{{ userStore.storeInfo.mobile }}</div>
          <div class="average marT20 flex flex-align-center" v-if="tabIndex === 0">
            <img :src="icon" alt="" class="iconImg">
            <div class="font20">
              温馨提示：考试前多做几次模拟考试，能多次稳定考90分以上再去考试
            </div>
          </div>
          <div class="average marT20 flex flex-align-center"
            v-if="tabIndex === 1 && !scoreList.some((item: any) => isToday(item.time))">
            <img :src="icon" alt="" class="iconImg">
            <div class="font20">
              您今天还没有模拟考
            </div>
          </div>
        </div>
      </div>
      <div class="flex flex-align-center flex-column" v-show="tabIndex == 0">
        <div class="score">{{ userStore.statisticsData.averageScore }}</div>
        <div class="average marT10">平均成绩</div>
      </div>
      <div v-show="tabIndex === 1" class="challenge">挑战榜单</div>
    </div>
  </div>
  <el-dialog v-model="clearModel" width="40%" :before-close="handleClose" :close-on-click-modal="false"
    :style="{ borderRadius: '10px', paddingBottom: '40px', border: '2px solid #d9d9d9' }">
    <div class="prompt">温馨提示</div>
    <div class="f40">您确定要清空科目一考试记录吗？</div>
    <template #footer>
      <div class="dialog-footer flex flex-align-center flex-justify-center">
        <div @click="clearModel = false" class="cancel cursor_pointer">取消</div>
        <div @click="confrim" class="sure marL30 cursor_pointer">清空</div>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import TabSwitcher from '@/components/tabbar/TabSwitcher.vue'
import './dialog.scss'
import { reactive, ref, onMounted, onUnmounted, nextTick } from 'vue'
import { Delete, CaretTop, CaretBottom } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import icon from '@/assets/img/icon.png'
import { getExamAll } from '@/api/userApi'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
// tab切换的下标
const tabIndex = ref(0)
const chartRef = ref<HTMLDivElement | null>(null)
const orderIndex = ref(0)
// 成绩数据
const scoreList = ref<any>([])
const clearModel = ref(false)
const handleTabChange = (index: number) => {
  console.log(index, '切换的下标')
  tabIndex.value = index
  if (index == 0) {
    nextTick(initChart)
  }
}
const chartDate = ref<any>([])
const chartScore = ref<any>([])
const initChart = () => {
  if (chartRef.value) {
    // 确保销毁之前的图表实例
    if (myChart) {
      myChart.dispose();
    }

    myChart = echarts.init(chartRef.value);
    const option = {
      xAxis: {
        type: 'category',
        data: chartDate.value,
        boundaryGap: false,
      },
      yAxis: {
        type: 'value',
        max: 100,
        min: 0, // 添加最小值确保从0开始
      },
      series: [
        {
          data: chartScore.value,
          type: 'line',
          color: '#32c45d',
          smooth: true, // 添加平滑效果
          markLine: {
            data: [
              {
                yAxis: 90,
                name: '及格线',
                label: {
                  formatter: '及格分: {c}',
                  color: '#32c45d',
                  backgroundColor: '#ebfaef',
                  height: 40,
                  width: 100,
                  borderRadius: 4,
                  align: 'center',
                  verticalAlign: 'middle',
                },
              },
            ],
            lineStyle: {
              type: 'dashed',
            },
          },
        },
      ],
      tooltip: { // 添加提示框
        trigger: 'axis'
      },
    };
    myChart.setOption(option);
  }
}
const formatDuration = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}'${secs.toString().padStart(2, '0')}`
}
const handleClose = () => {
  clearModel.value = false
}
const confrim = () => {
  clearModel.value = false
}
const handleResize = () => {
  if (myChart) {
    myChart.resize()
    setTimeout(() => myChart?.resize(), 200);
  }
}

const getData = async () => {
  const res = await getExamAll({
    memberId: userStore.storeInfo.memberId,
    carModelId: userStore.storeInfo.carModelId,
    categoryId: userStore.categoryId
  })
  if (res.code === '00000' && res.data) {
    scoreList.value = res.data.map((e: any) => {
      return {
        score: e.score,
        seconds: e.duration,
        time: e.createTime.slice(0, 16)
      }
    })

    // 获取当前时间到前十五天之间的数据
    const now = new Date();
    const fifteenDaysAgo = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 14, 0, 0, 0, 0); // 包含今天，共15天
    let timeFrame = res.data
      .filter((e: any) => {
        const createDate = new Date(e.createTime);
        return createDate >= fifteenDaysAgo && createDate <= now;
      })
      .map((e: any) => {
        return {
          score: e.score,
          seconds: e.duration,
          time: e.createTime.slice(0, 10)
        }
      })
    console.log(timeFrame, "timeFrame===");
    chartDate.value = timeFrame.map((e: any) => e.time)
    chartScore.value = timeFrame.map((e: any) => e.score)
    console.log(chartDate.value, "chartDate.value===");
    console.log(chartScore.value, "chartScore.value===");

  }
}
const isToday = (date: any) => {
  const inputDate = new Date(date);
  const today = new Date();

  return (
    inputDate.getDate() === today.getDate() &&
    inputDate.getMonth() === today.getMonth() &&
    inputDate.getFullYear() === today.getFullYear()
  );
};

onMounted(async () => {
  await getData()
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (myChart) {
    myChart.dispose() // 销毁实例，释放资源
    myChart = null
  }
})
const timeOrder = () => {
  orderIndex.value = orderIndex.value == 0 ? 1 : 0
}
let myChart: echarts.ECharts | null = null
</script>
<style lang="scss" scoped>
@use 'sass:math';

@function rem($px) {
  @return math.div($px, 16) * 1rem;
}

.score_bg {
  position: fixed;
  top: rem(182);
  left: 50%;
  margin-left: -27%;
  width: 54%;
  height: rem(170);
  background-color: #fff;
  padding-top: rem(40);
}

.scoreInfo {
  width: 100%;
  height: rem(130);
  background-color: #fff;
  border-radius: rem(8);
  box-shadow: 0 rem(2) rem(6) #ccc;
  transition: all 0.3s ease;
  padding: 0 rem(40);

  &:hover {
    transform: translateY(rem(-5));
    /* 上移10像素 */
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
    /* 悬停时更明显的阴影 */
    cursor: pointer;
  }
}

.headerPic {
  width: rem(100);
  height: rem(100);
  border-radius: 50%;
}

.phone {
  font-size: rem(35);
  color: #333;
  font-weight: 600;
}

.score {
  color: #ff6060;
  font-size: rem(45);
}

.average {
  font-size: rem(25);
  color: #a2a2a2;
}

.challenge {
  color: #32c45d;
  font-size: rem(40);
  font-weight: bold;
}

.chartStyle {
  width: 100%;
  height: rem(450);
}

.score-content {
  margin: rem(250) 18% rem(50);
}

.score-title {
  color: #333;
  font-size: rem(32);
  font-weight: bold;
}

.font26 {
  font-size: rem(26);
  color: #4a4a4a;
}

.container {
  height: calc(100vh - rem(92) - rem(90));
  overflow: auto;
}

.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  justify-items: center;
}

.bgTitle {
  background-color: #f7f7f7;
  height: rem(70);
  border-radius: rem(50);
  line-height: rem(70);
}

.f35 {
  font-size: rem(35);
  color: #666666;
}

.tips {
  color: #ff6262;
  font-size: rem(35);
}

.pass {
  color: #32c45d;
  font-size: rem(35);
}

.fh35 {
  font-size: rem(35);
  color: #999;
}

.score_ft {
  font-size: rem(35);
  color: #333;
}

.ranking {
  padding: rem(40) 0;
}

.prompt {
  font-size: rem(50);
  color: #333;
  font-weight: bold;
  margin-left: rem(40);
}

.f40 {
  font-size: rem(40);
  color: #333;
  margin: rem(200) 0 rem(130) rem(60);
  text-align: center;
}

.cancel,
.sure {
  width: rem(400);
  height: rem(100);
  border-radius: rem(50);
  text-align: center;
  line-height: rem(100);
  font-size: rem(40);
}

.cancel {
  background-color: #fff;
  color: #32c45d;
  border: 2px solid #32c45d;
}

.sure {
  background-color: #32c45d;
  color: #fff;
}

.marL8 {
  margin-left: rem(8);
}

.iconImg {
  width: rem(20);
  height: rem(20);
}

.font20 {
  font-size: rem(17);
  color: #ff6060;
}
</style>
